package com.coldwindblows.blog.controller.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.coldwindblows.blog.bo.RestResponseBo;
import com.coldwindblows.blog.constant.WebConst;
import com.coldwindblows.blog.controller.BaseController;
import com.coldwindblows.blog.dto.MetaDto;
import com.coldwindblows.blog.dto.Types;
import com.coldwindblows.blog.service.IMetaService;

/**
 * Created by ColdWindBlows on 2018/07/06
 *
 */
@Controller
@RequestMapping("/admin/category")
@SuppressWarnings("rawtypes")
public class CategoryController extends BaseController {
	
	@Autowired
	private IMetaService metaService;
	
	@GetMapping("")
	public String index(Model model) {
		List<MetaDto> categories = metaService.getMetaList(Types.CATEGORY.getType(), null, WebConst.MAX_POSTS);
		List<MetaDto> tags = metaService.getMetaList(Types.TAG.getType(), null, WebConst.MAX_POSTS);
		model.addAttribute("categories", categories);
		model.addAttribute("tags", tags);
		return "admin/category";
	}
	
	@PostMapping("/save")
	@ResponseBody
	public RestResponseBo saveCategory(@RequestParam String cname, @RequestParam Integer mid) {
		try {
			metaService.insertMeta(Types.CATEGORY.getType(), cname, mid);
		} catch(Exception e) {
			String msg = "分类保存失败";
			return RestResponseBo.fail(msg);
		}
		return RestResponseBo.ok();
	}
	
	@PostMapping("/delete")
	@ResponseBody
	public RestResponseBo delete(@RequestParam Integer mid) {
		try {
			metaService.deleteMeta(mid);
		} catch(Exception e) {
			String msg = "删除失败";
			return RestResponseBo.fail(msg);
		}
		
		return RestResponseBo.ok();
	}
}
